<template>
	<!-- <view style="position: absolute;
    top: 109px;
    left: 0;
    z-index: 999;
    background: #fff;"> -->
	<!-- <input type="text" v-model="ssid" placeholder="ssid" /> -->
	<!-- <input type="text" v-model="password" placeholder="password" /> -->
	<!-- <input type="text" v-model="ip" placeholder="ip" /> -->
	<!-- <input type="text" v-model="port" placeholder="port" /> -->
	<!-- <button @click="connectWifi(ssid,password)">连接</button> -->
	<!-- <button @click="startLocalServiceDiscovery">搜索设备</button> -->
	<!-- </view> -->
	<u-popup :show="show" @close="close" mode="center" round="17rpx" :closeable="!isPrinting"
		:safeAreaInsetBottom="false">
		<view class="print">
			<template v-if="!isWifi">
				<view class="text">
					请先切换至本地wifi网络！
				</view>
			</template>
			<template v-else>
				<template v-if="!isPrinting&&status == 0">
					<view class="model">
						{{ `${skuData.phoneModel}-${skuData.material}`}}
					</view>
					<view class="tips">
						请确认当前设备的IP:
					</view>
					<input type="text" v-model="skuData.address" placeholder="输入IP或扫描设备码" />
					<image src="../../static/images/icon/saoma.png" mode="aspectFit" class="image" @click="scanCode">
					</image>
					<!-- <input type="text" v-model="port" placeholder="port" /> -->
					<view class="button" @click="print">
						立即打印
					</view>
				</template>
				<template v-if="isPrinting&&status == 1">
					<u-loading-icon mode="circle" size="60"></u-loading-icon>
					<view class="text">
						准备中，请勿关闭当前页面…
					</view>
				</template>
				<template v-if="!isPrinting&&status == 2">

					<view class="text">
						手机壳打印中，请稍作等待
					</view>
					<view class="button" @click="close()" style="margin-top: 70rpx;">
						确定
					</view>
				</template>
				<template v-if="!isPrinting&&status == 3">
					<view class="text">
						{{erroMsg}}
					</view>
					<view class="button" @click="retry" style="margin-top: 70rpx;">
						重试
					</view>
				</template>
			</template>

		</view>
	</u-popup>
</template>

<script>
	import {
		getPrintImage,
		getCustomDetail
	} from '@/api/custom.js'
	export default {
		name: "to-print",
		data() {
			return {
				show: false,
				isPrinting: false,
				status: 0, //0未开始 1准备中 2已完成 3失败
				skuData: {
					phoneModel: '',
					material: '',
					id: '',
					address: '',
					port: ''
				},
				printImageUrl: '',
				productPoint: {},
				timeout: 40 * 1000,
				isWifi: true,
				erroMsg: '打印异常，请稍后重试',
				tcpSocket:null,
				/*  */
			};
		},
		methods: {
			// 初始化wifi模块
			initWifi() {
				const _this = this
				wx.startWifi({
					success(res) {
						console.log(res.errMsg)

						_this.onWifiConnected()
						// _this.getScope()
					},
					fail(res) {
						console.log(res.errMsg)
					}
				})
			},
			// 获取授权
			// getScope() {
			// 	const deviceInfo = wx.getDeviceInfo()
			// 	wx.getSetting({
			// 		success(res) {
			// 			if (!res.authSetting['scope.userLocation']) {
			// 				wx.authorize({
			// 					scope: 'scope.userLocation',
			// 					success() {
			// 						if (deviceInfo.platform == "android") {
			// 							this.getWifiList()
			// 						} else {
			// 							this.getWifiList()
			// 						}
			// 					},
			// 					fail(err) {}
			// 				})
			// 			} else {
			// 				if (deviceInfo.platform == "android") {
			// 					this.getWifiList()
			// 				} else {
			// 					this.getWifiList()
			// 				}
			// 			}
			// 		}
			// 	})

			// },
			// 获取wifi列表
			// getWifiList() {
			// 	const _this = this
			// 	wx.getWifiList({
			// 		success(res) {
			// 			console.log(res)
			// 			_this.onGetWifiList()
			// 		},
			// 		fail(res) {
			// 			console.log(res.errMsg)
			// 		}
			// 	})
			// },
			// 获取到 Wi-Fi 列表数据事件
			// onGetWifiList() {
			// 	wx.onGetWifiList((res) => {
			// 		// 获取到wifi列表 识别指定wifi并自动连接
			// 		console.log(res);
			// 	})
			// },
			// // 连接wifi
			// connectWifi(SSID, password) {
			// 	wx.connectWifi({
			// 		SSID,
			// 		password,
			// 		success(res) {
			// 			console.log(res.errMsg)
			// 		},
			// 		fail(err) {
			// 			console.log(err)
			// 		}
			// 	})
			// },
			// 连接上 Wi-Fi 的事件回调
			onWifiConnected() {
				wx.onWifiConnected((res) => {
					console.log('onWifiConnected', res);
					if (res.wifi.SSID != '') {
						this.isWifi = true
					} else {
						this.isWifi = false
					}

					// 连接上wifi后，搜索同一局域网下设备，找到打印机ip
					// this.getConnectedWifi()

				})
			},
			// 获取wifi的信息，判断与设备是否处于同一局域网下
			// getConnectedWifi() {
			// 	const _this = this
			// 	wx.getConnectedWifi({
			// 		success(res) {
			// 			console.log('getConnectedWifi', res)
			// 			_this.startLocalServiceDiscovery()
			// 		}
			// 	})
			// },
			// 搜寻局域网下设备
			// startLocalServiceDiscovery() {
			// 	console.log('搜寻局域网下设备');
			// 	wx.onLocalServiceFound(function(res) {
			// 		console.log('发现服务:', res);
			// 	});

			// 	// 启动服务发现
			// 	wx.startLocalServiceDiscovery({
			// 		serviceType: '_http._tcp.',
			// 		success: function() {
			// 			console.log('服务发现启动成功');
			// 		},
			// 		fail: function(err) {
			// 			console.error('服务发现启动失败:', err);
			// 		}
			// 	});

			// 	// 停止服务发现
			// 	setTimeout(() => {
			// 		wx.stopLocalServiceDiscovery({
			// 			success: function() {
			// 				console.log('服务发现已停止');
			// 			},
			// 			fail: function(err) {
			// 				console.error('停止服务发现失败:', err);
			// 			}
			// 		});
			// 	}, 30000); // 30秒后自动停止
			// },


			/* 连接打印机设备 */
			// 开启连接
			connectToServer() {
				console.log('TCP 开始连接');
				this.tcpSocket = wx.createTCPSocket()
				this.tcpSocket.onConnect(() => {
					console.log('TCP 连接成功');
					this.getPrintImage()
				});

				// 监听接收到的数据
				this.tcpSocket.onMessage((res) => {
					const message = new TextDecoder().decode(res.message);
					console.log('接收到的数据:', message);
				});

				// 监听错误
				this.tcpSocket.onError((error) => {
					console.error('TCP 连接错误:', error);
					this.status = 3
					this.erroMsg = '未能成功连接到设备，请确保连接上本地wifi'
					this.isPrinting = false
					this.printImageUrl = ''
				});

				// 关闭连接
				this.tcpSocket.onClose(() => {
					console.log('TCP 连接关闭');
				});

				this.tcpSocket.connect({
					address: this.skuData.address,
					port: this.skuData.port
				})
			},
			// 发送打印信息
			sendPrint() {
				// 发送数据
				const data = {
					productPoint: this.productPoint,
					printImageUrl: this.printImageUrl,
				};
				this.tcpSocket.write(JSON.stringify(data));
				this.isPrinting = false
				this.status = 2
				this.tcpSocket.close()
			},
			// 获取打印图片
			getPrintImage() {
				const _this = this
				let timer = null
				let timer1 = null
				// 发送打印请求
				getPrintImage({
					id: this.skuData.id
				}).then(res => {
					getDetail()
				})

				function getDetail() {
					timer = setInterval(() => {
						if (_this.printImageUrl == '') {
							getCustomDetail({
									id: _this.skuData.id
								}).then(res => {
									if (res.data.printImageUrl != '') {
										_this.printImageUrl = res.data.printImageUrl
										_this.productPoint = res.data.productPoint
										clearInterval(timer)
										clearInterval(timer1)
										_this.sendPrint()
									}
								})
								.catch(() => {
									clearInterval(timer)
									clearInterval(timer1)
									_this.isPrinting = false
									_this.status = 3
									_this.erroMsg = '打印异常，请稍后重试'
								})
						} else {
							clearInterval(timer)
							clearInterval(timer1)
							// _this.connectToServer()
							// console.log('传输给打印机');
						}
					}, 5000)
				}
				
				// 定时超时
				let timeout = _this.timeout
				timer1 = setInterval(() => {
					timeout = timeout - 1000
					if (timeout <= 0) {
						clearInterval(timer)
						clearInterval(timer1)
						_this.isPrinting = false
						_this.status = 3
						_this.erroMsg = '打印异常，请稍后重试'
					}
				}, 1000)
			},
			// 打印
			print() {
				this.printImageUrl = ''
				this.isPrinting = true
				this.status = 1
				this.connectToServer()

			},
			// 重试
			retry() {
				this.printImageUrl = ''
				this.isPrinting = false
				this.status = 0
			},
			// 调起扫码
			scanCode() {
				const _this = this
				wx.scanCode({
					success(res) {
						if (res.scanType == 'WX_CODE' && res.path) {
							console.log(res.path);
							const storeIpIndex = unescape(res.path).indexOf('ip')
							if (storeIpIndex != -1) {
								let ip = unescape(res.path).split('=')[2]
								_this.skuData.address = ip.split(':')[0]
								_this.skuData.port = ip.split(':')[1]
							} else {
								uni.showToast({
									title: '扫描内容无效',
									icon: 'none'
								})
							}
						} else {
							uni.showToast({
								title: '扫描内容无效',
								icon: 'none'
							})
						}
					},
					fail() {
						uni.showToast({
							title: '扫描内容无效',
							icon: 'none'
						})
					}
				})
			},
			init(data) {
				console.log('调用打印模块', data);
				this.status = 0
				this.skuData = data
				this.show = true
				// const deviceInfo = wx.getDeviceInfo()
				// console.log(deviceInfo);
				this.initWifi()
				// this.connectToServer()
			},
			close() {
				console.log('关闭');
				if (this.isPrinting) {
					return
				}
				this.show = false
			}
		},
		mounted() {
			this.initWifi()
		}
	}
</script>

<style lang="scss">
	.print {
		height: 320rpx;
		width: 50vw;
		margin: 70rpx 70rpx 30rpx;

		.model {
			font-size: 28rpx;
			font-weight: bold;
			margin-bottom: 17rpx;
			white-space: nowrap;
		}

		.tips {
			font-size: 23rpx;
			margin-bottom: 17rpx;
		}

		input {
			border: 2rpx solid #ccc;
			border-radius: 17rpx;
			height: 68rpx;
			padding: 0px 37rpx;
			box-sizing: border-box;
			font-size: 25rpx;
			margin-bottom: 50rpx;
			width: calc(50vw - 70rpx);
			display: inline-block;
		}

		.image {
			height: 50rpx;
			width: 50rpx;
			display: inline-block;
			margin-bottom: 60rpx;
			margin-left: 17rpx;
		}

		.button {
			width: 250rpx;
			height: 78.8rpx;
			border-radius: 78rpx;
			font-size: 35rpx;
			box-sizing: border-box;
			text-align: center;
			line-height: 78.8rpx;
			background-color: #333;
			color: #fff;
			margin: auto;
		}

		.text {
			text-align: center;
			margin: 30rpx 0;
			font-size: 28rpx;
		}
	}
</style>